package edu.csu.smartpark;

import edu.csu.smartpark.model.common.BusinessException;
import edu.csu.smartpark.model.common.MsgEntity;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

@Slf4j
@ControllerAdvice
@ResponseBody
public class ControllerExceptionHandler {
    @ExceptionHandler(BusinessException.class)
    public MsgEntity businessExceptionHandle(BusinessException ex) {
        log.error("[Smart Park Server] Business execution failed - "+ex.getClass().getName() + ":" + ex.getMessage());
        return new MsgEntity("ERROR", ex.getCode(),"[Smart Park Server] Business execution failed: " + ex.getMessage());
    }

    @ExceptionHandler(UnauthorizedException.class)
    @ResponseStatus(value= HttpStatus.FORBIDDEN)
    public MsgEntity unauthorizedExceptionHandle(UnauthorizedException ex) {
        return new MsgEntity("ERROR","-1","[Smart Park Server] Unauthorized: " + ex.getMessage());
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(value= HttpStatus.INTERNAL_SERVER_ERROR)
    public MsgEntity systemUnexpectedExceptionHandle(Exception ex) {
        log.error("[Smart Park Server] SYSTEM FAIL - "+ex.getClass().getName(), ex.getMessage());
        ex.printStackTrace();
        return new MsgEntity("ERROR","-1","[Smart Park Server] "+ex.getClass().getName()+": "+ex.getMessage());
    }
}
